package com.woniu.userservice.util;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
/**
 * @Auther: 李浪  <br/>
 * @Date: 2020/3/18:22:46  <br/>
 * @Description:图片上传工具类
 */
public class FtpUtil {
    //资源服务器主机
    private final static String HOSTNAME = "106.12.25.67";
    //ftp连接使用端口
    private final static int PORT = 21;

    private final static String BASE_FILE_URL = "http://106.12.25.67";
    private final static String BASE_FILE_STORE_PATH = "/home/ftpuser/health/";
    private final static String USERNAME = "ftpuser";
    private final static String PASSWORD = "lilang123";
    private final static String[] FILE_RELATIVE_PATHS = {"/images/", "/video/", "/pdf/", "/music/"};
    private final static String OTHER_FILE_RELATIVE_PATH = "/other/";
    private final static Map<String, String> SUFFIX_RELATIVE_PATH_MAP = new HashMap<String, String>(8, 1) {
        {
            put(".png", FILE_RELATIVE_PATHS[0]);
            put(".jpg", FILE_RELATIVE_PATHS[0]);
            put(".mp4", FILE_RELATIVE_PATHS[1]);
            put(".pdf", FILE_RELATIVE_PATHS[2]);
            put(".mp3", FILE_RELATIVE_PATHS[3]);
        }
    };

    public static String upload(InputStream fileInputStream, String fileName) {
        //非空判断
        if (fileName == null) {
            return null;
        }
        //将原始文件名转换为uuidName,并做了后缀名lowercase处理
        fileName = getUUIDFileName(fileName);

        //文件类型处理，文件路径初始化
        String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
        String suffixRelativePath = SUFFIX_RELATIVE_PATH_MAP.get(fileSuffix.toLowerCase());

        //增加上传所有文件类型到功能
        if (suffixRelativePath == null) {
            suffixRelativePath = OTHER_FILE_RELATIVE_PATH;
        }
        String fileUrl = BASE_FILE_URL + suffixRelativePath + fileName;

        //创建ftp客户端
        FTPClient ftpClient = new FTPClient();

        try {
            //链接ftp服务器
            ftpClient.connect(HOSTNAME, PORT);
            //登录ftp
            ftpClient.login(USERNAME, PASSWORD);
            int replyCode = ftpClient.getReplyCode();
            //如果reply返回230就算成功了，如果返回530密码用户名错误
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                ftpClient.disconnect();
                System.out.println("文件服务器连接失败,replyCode: " + replyCode);
                return null;
            }

            //ftp参数设置
            ftpClient.setControlEncoding("UTF-8");
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.changeWorkingDirectory(BASE_FILE_STORE_PATH + suffixRelativePath);
            //传输
            boolean storeSuccess = ftpClient.storeFile(fileName, fileInputStream);
            try {
                if (!storeSuccess) {
                    System.out.println("上传失败：" + ftpClient.getReplyString());
                    return null;
                } else {
                    return fileUrl;
                }
            } finally {
                fileInputStream.close();
                ftpClient.logout();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    }

    private static String getUUIDFileName(String originalFilename) {
        return System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
    }
}
